<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>小球动画1</title>
		<style>
			/*div{
				color: hsl(360,1,0.5);
			}*/
		</style>
	</head>
	<body>
	</body>
	<script src="jquery.js"></script>
	<script>
		$("body").css("margin","0");
		
		var hue = Math.random()*360;
		var dia = 40+Math.random()*110;
//		alert($(window).width());
		
		var left = ($(window).width()-dia)*Math.random();
		var top1 = ($(window).height()-dia)*Math.random();
		
		
		$("<div></div>").css({
			"background-color":"hsl("+hue+",100%,50%)",
			width:dia,
			height:dia,
			"border-radius":"50%"
		}).appendTo("body").offset({left:left,top:top1});
		
		
		//随机生成x方向的速度和y方向的速度
		//把速度限定在-3到-0.5和0.5到3之间。
		var xSpeed = Math.random()*5-3;
		xSpeed = xSpeed>-0.5?xSpeed+1:xSpeed;
		
		var ySpeed = Math.random()*5-3;
		ySpeed = ySpeed>-0.5?ySpeed+1:ySpeed;
		
		function move(){
			var x = $("div").offset().left;
			var y = $("div").offset().top;
			
			if(x+xSpeed<=0){
				xSpeed = Math.abs(xSpeed);
			}
			
			if(x+xSpeed>=$(window).width()-dia){
				xSpeed = -Math.abs(xSpeed);
			}
			
			if(y+ySpeed<=0){
				ySpeed = Math.abs(ySpeed);
			}
			
			if(y+ySpeed>=$(window).height()-dia){
				ySpeed = -Math.abs(ySpeed);
			}
			
			x+=xSpeed;
			y+=ySpeed;
			
			$("div").offset({
				left:x,
				top:y
			});
			
			requestAnimationFrame(move);
		}
		
		requestAnimationFrame(move);
		
		
	</script>
</html>
